﻿using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Runtime;
using System.Runtime.Caching;

namespace NCP.Core
{
    public class HttpRuntimeCache : ICacheService
    {
        public void Add<V>(string key, V value)
        {
            ObjectCache cache = MemoryCache.Default;
            cache[key] = value;
        }
        public void Add<V>(string key, V value, int cacheDurationInSeconds)
        {
            MemoryCache.Default.Add(key, value, new CacheItemPolicy()
            {
                AbsoluteExpiration = DateTime.Now.AddSeconds(cacheDurationInSeconds)
            });
        }
        public bool ContainsKey<V>(string key)
        {
            return MemoryCache.Default.Contains(key);
        }
        public V Get<V>(string key)
        {
            return (V)MemoryCache.Default.Get(key);
        }
        public IEnumerable<string> GetAllKey<V>()
        {
            var keys = new List<string>();
            foreach (var cacheItem in MemoryCache.Default)
            {
                keys.Add(cacheItem.Key);
            }
            return keys;
        }
        public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
        {
            var cacheManager = MemoryCache.Default;
            if (cacheManager.Contains(cacheKey))
            {
                return (V)cacheManager[cacheKey];
            }
            else
            {
                var result = create();
                cacheManager.Add(cacheKey, result, new CacheItemPolicy()
                {
                    AbsoluteExpiration = DateTime.Now.AddSeconds(cacheDurationInSeconds)
                });
                return result;
            }
        }
        public void Remove<V>(string key)
        {
            MemoryCache.Default.Remove(key);
        }
    }
}
